package translations

import (
	"fmt"
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	en_translations "github.com/go-playground/validator/v10/translations/en" // 提示语翻译包
	zh_translations "github.com/go-playground/validator/v10/translations/zh"
)

var (
	uni *ut.UniversalTranslator
)

func InitValidate(local string) (*validator.Validate, ut.Translator) {
	validate := validator.New()

	// en 英文，zh 中文
	en := en.New()
	zh := zh.New()
	//初始化翻译器，并指定支持的语种
	uni = ut.New(zh, en, zh)
	// 获取指定语种的翻译器
	trans, _ := uni.GetTranslator(local)

	switch local {
	case "en":
		en_translations.RegisterDefaultTranslations(validate, trans)
	case "zh":
		zh_translations.RegisterDefaultTranslations(validate, trans)
	default:
		zh_translations.RegisterDefaultTranslations(validate, trans)
	}

	return validate, trans
}

func TranslateAll() {
	type User struct {
		UserName string `validate:"required"`
		Tagline  string `validate:"required,lt=10"`
		Tagline2 string `validate:"required,gt=1"`
	}
	user := User{
		Tagline:  "kkk is a good boy",
		Tagline2: "",
	}

	validate, trans := InitValidate("zh")
	err := validate.Struct(user)

	if err != nil {
		errs := err.(validator.ValidationErrors)

		// 一次性将所有字段的提示消息翻译出来
		fmt.Println(errs.Translate(trans))

		// 逐条翻译
		for _, e := range errs {
			fmt.Println(e.Translate(trans))
		}
	}

}
